package com.dzt.cloudreader.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;

import com.dzt.cloudreader.R;
import com.dzt.cloudreader.base.SuperFragment;
import com.dzt.cloudreader.rxbus.RxBus;
import com.dzt.cloudreader.rxbus.RxCodeConstants;

import java.util.ArrayList;

import butterknife.BindView;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by M02323 on 2017/12/15.
 */

public class BookFragment extends SuperFragment {
	@BindView(R.id.tab_book)
	TabLayout tabLayout;
	@BindView(R.id.vp_book)
	ViewPager viewPager;
	private ArrayList<String> mTitleList = new ArrayList<>(3);
	private ArrayList<Fragment> mFragments = new ArrayList<>(3);

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_book;
	}

	@Override
	protected void initWidgets() {
		mTitleList.add("生活");
		mTitleList.add("文学");
		mTitleList.add("文化");
		mFragments.add(BookCustomFragment.newInstance("生活"));
		mFragments.add(BookCustomFragment.newInstance("文学"));
		mFragments.add(BookCustomFragment.newInstance("文化"));
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		/**
		 * 注意使用的是：getChildFragmentManager，
		 * 这样setOffscreenPageLimit()就可以添加上，保留相邻3个实例，切换时不会卡
		 * 但会内存溢出，在显示时加载数据
		 */
		MyFragmentPagerAdapter myAdapter = new MyFragmentPagerAdapter(getChildFragmentManager(), mFragments, mTitleList);
		viewPager.setAdapter(myAdapter);
		// 左右预加载页面的个数
		viewPager.setOffscreenPageLimit(3);
		myAdapter.notifyDataSetChanged();
		tabLayout.setTabMode(TabLayout.MODE_FIXED);
		tabLayout.setupWithViewPager(viewPager);
		// item点击跳转
		initRxBus();
	}

	/**
	 * 每日推荐点击"更多"跳转
	 */
	private void initRxBus() {
		Subscription subscription = RxBus.getDefault().toObservable(RxCodeConstants.JUMP_TYPE, Integer.class)
				.subscribe(new Action1<Integer>() {
					@Override
					public void call(Integer integer) {
						if (integer == 0) {
							viewPager.setCurrentItem(3);
						} else if (integer == 1) {
							viewPager.setCurrentItem(1);
						} else if (integer == 2) {
							viewPager.setCurrentItem(2);
						}
					}
				});
		addSubscription(subscription);
	}
}
